﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using ESRI.ArcGIS.Geodatabase;
using MyEngineExercise.我的扩展;
using ESRI.ArcGIS.Geometry;
using System.Text.RegularExpressions;
using MyEngineExercise.我的扩展.信息类;
using System.IO;

namespace MyEngineExercise.工作.分割图层_20120810
{
    public partial class Form_clip_main : Form
    {

        private IFeatureClass _featureClass_original = null;
        private IPolygon _unionned_polygon_original = null;
        private IEnvelope _old_envelop = null;

        private string _shpFullPath = string.Empty;

        private int _square_length = 0;
        private int _length_original = 0;
        private string _unit = string.Empty;

        private List<string> _field_name_list = new List<string>();

        //旧envelop长宽
        private double _old_envelop_width = 0;
        private double _old_envelop_height = 0;

        //envelop左下角坐标(新旧都一样)
        private double _envelop_lower_left_x = 0;
        private double _envelop_lower_left_y = 0;


        public Form_clip_main()
        {
            InitializeComponent();
        }



        private void button_open_shp_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfileDialog = new OpenFileDialog();
            openfileDialog.InitialDirectory = "E:\\";
            openfileDialog.Filter = "shapefile文件|*.shp|mdb文件|*.mdb";
            openfileDialog.Title = "打开shp或mdb";
            if (openfileDialog.ShowDialog() == DialogResult.OK)
            {
                this.textBox_shp_path.Text = openfileDialog.FileName;
                _shpFullPath = openfileDialog.FileName;
                //Debug.Print("shapefile路径为：" + openfileDialog.FileName);
                if (System.IO.Path.GetExtension(openfileDialog.FileName) == ".shp")
                {
                    Debug.Print("打开了shp。");
                    _featureClass_original = MyAeMethods.Instance.NewFeatureClass(openfileDialog.FileName);
                }
                else if (System.IO.Path.GetExtension(openfileDialog.FileName) == ".mdb")
                {
                    Debug.Print("打开了mdb。");
                re_write_fc_name:
                    Form_write_featureclass_name form_write_featureclass_name = new Form_write_featureclass_name();
                    if (form_write_featureclass_name.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            _featureClass_original = MyAeMethods.Instance.NewMdbFeatureWorkspace(openfileDialog.FileName).OpenFeatureClass(form_write_featureclass_name.Get_fc_name);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show("找不到featureClass，请检查featureClass是否存在？大小写有没有错？名称是否有空格？\n" + ex.Message);
                            goto re_write_fc_name;
                        }

                    }
                    else
                        return;

                }

                _unionned_polygon_original = _featureClass_original.UnionPolygons(null);

                //获取多边形的外接矩形（旧）
                _old_envelop = _unionned_polygon_original.Envelope;

                Debug.Print("_old_envelop.Width:" + _old_envelop.Width);
                Debug.Print("_old_envelop.Height:" + _old_envelop.Height);
                Debug.Print("_old_envelop.LowerLeft.x:" + _old_envelop.LowerLeft.X);
                Debug.Print("_old_envelop.LowerLeft.y:" + _old_envelop.LowerLeft.Y);
                Debug.Print("_old_envelop.UpperRight.x:" + _old_envelop.UpperRight.X);
                Debug.Print("_old_envelop.UpperRight.y:" + _old_envelop.UpperRight.Y);

                _old_envelop_width = _old_envelop.Width;
                _old_envelop_height = _old_envelop.Height;

                //左下角坐标（新旧envelop都一样）
                _envelop_lower_left_x = _old_envelop.LowerLeft.X;
                _envelop_lower_left_y = _old_envelop.LowerLeft.Y;

            }
            else
                return;
        }



        private void button_open_txt_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfileDialog = new OpenFileDialog();
            openfileDialog.Filter = "txt文件|*.txt";
            openfileDialog.Title = "打开shp或mdb";
            if (openfileDialog.ShowDialog() == DialogResult.OK)
            {
                this.textBox_txt_field_path.Text = openfileDialog.FileName;
            }
        }



        private void button_start_Click(object sender, EventArgs e)
        {
            if (this.textBox_shp_path.Text == string.Empty)
            {
                MessageBox.Show("请先选择shp路径！","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }

            if (this.textBox_square_length.Text == string.Empty)
            {
                MessageBox.Show("长度不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            Regex regex = new Regex(@"^[0-9]+$");
            if (regex.IsMatch(this.textBox_square_length.Text) == false)
            {
                MessageBox.Show("长度只能输入整数！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            _square_length = _length_original = Convert.ToInt32(this.textBox_square_length.Text);
            if (this.radioButton_kilometer.Checked == true)
            {
                _square_length = _square_length * 1000;
                _unit = "公里";
            }
            else if (this.radioButton_meter.Checked == true)
            {
                _unit = "米";
            }



            using (StreamReader sr = new StreamReader(this.textBox_txt_field_path.Text))
            {
                Regex regex_txt = new Regex(@"^[0-9a-zA-Z_\u4e00-\u9fa5]+$");
                string line = string.Empty;
                while (null != (line = sr.ReadLine()))
                {
                    Debug.Print("当前line的值为:" + line);
                    Debug.Print("当前line的长度为:" + line.Length.ToString());
                    if (regex_txt.IsMatch(line) == false)
                    {
                        _field_name_list = new List<string>();
                        MessageBox.Show("txt文件格式错误!\n（1）只允许输入汉字、大小写字母、数字和下划线，不允许有空格和行与行之间不能有空行\n（2）如果字段包含汉字，则txt文件必须是UTF-8格式编码\n（3）每行填写一个字段名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    
                    if (line.Length > 10)
                    {
                        _field_name_list = new List<string>();
                        MessageBox.Show("字段名称太长了，不能超过10个字符(即5个汉字或10个英文字母)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    _field_name_list.Add(line);
                }
            }

            foreach (var asd in _field_name_list)
            {
                Debug.Print("从txt读到的字段名：" + asd);
            }


            Start_cut();
        }



        public void Start_cut()
        {
            #region 构造一个新的矩形
            int new_envelop_width = Convert.ToInt32(_old_envelop_width / _square_length) * _square_length + _square_length;
            int new_envelop_height = Convert.ToInt32(_old_envelop_height / _square_length) * _square_length + _square_length;

            Debug.Print("new_envelop_width构建前:" + new_envelop_width.ToString());
            Debug.Print("new_envelop_height构建前:" + new_envelop_height.ToString());

            Envelope new_envelop = new EnvelopeClass();
            new_envelop.PutCoords(_envelop_lower_left_x, _envelop_lower_left_y, _envelop_lower_left_x + Convert.ToDouble(new_envelop_width), _envelop_lower_left_y + Convert.ToDouble(new_envelop_height));

            Debug.Print("new_envelop.Width构建后：" + new_envelop.Width.ToString());
            Debug.Print("new_envelop.Height构建后:" + new_envelop.Height.ToString());
            #endregion


            //根据新的envelop的长和宽，构建n个面积相等的正方形，保存到一个新的shp文件中，一个正方形是一条记录
            List<IEnvelope> envelop_list = new List<IEnvelope>();
            double new_lower_left_x = new_envelop.LowerLeft.X;
            double new_lower_left_y = new_envelop.LowerLeft.Y;

            double test_x = new_lower_left_x;
            double text_y = new_lower_left_y;

            MyAeMethods.Instance.SetBusyState();

            //从左下角开始构建,从左到右，从下到上
            for (int j = 0; j < new_envelop_height / _square_length; j++)//y方向
            {
                Debug.Print("---------------------------------");
                for (int i = 0; i < new_envelop_width / _square_length; i++)//x方向
                {
                    IEnvelope envelop = new EnvelopeClass();
                    envelop.PutCoords(new_lower_left_x, new_lower_left_y, new_lower_left_x + _square_length, new_lower_left_y + _square_length);
                    Debug.Print(string.Format("{0}   {1}   {2}   {3}", new_lower_left_x - test_x, new_lower_left_y - text_y, new_lower_left_x + _square_length - test_x, new_lower_left_y + _square_length - text_y));
                    //Debug.Print(string.Format("{0}   {1}   {2}   {3}", new_lower_left_x , new_lower_left_y , new_lower_left_x + length , new_lower_left_y + length ));
                    new_lower_left_x += _square_length;
                    envelop_list.Add(envelop);
                }
                new_lower_left_y += _square_length;
                new_lower_left_x = new_envelop.LowerLeft.X;//还原
                Debug.Print("---------------------------------");
            }


            Debug.Print("envelop_list.Count:" + envelop_list.Count.ToString());

            MyAeMethods.Instance.SetDefaultState();

            string savePath1 = System.IO.Path.GetDirectoryName(_shpFullPath) + "\\" + System.IO.Path.GetFileNameWithoutExtension(_shpFullPath) + "_切割前_" + MyMethods.Date_time_suffix();

            Debug.Print("savePath1:" + savePath1);

            //创建featureclass（空的，里面没有数据）
            //IFeatureClass featureClass_no_clip = MyAeMethods.Instance.CreateRedLineFeatureClass(savePath1);
            IFeatureClass featureClass_no_clip = MyAeMethods.Instance.Create_custom_field_FeatureClass(savePath1, _field_name_list);
            
            if (null == featureClass_no_clip)
            {
                MessageBox.Show("无法创建空的FeatureClass，请尝试将保存的shp起另外一个名字。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MyAeMethods.Instance.SetDefaultState();
                return;
            }


            MyAeMethods.Instance.SetBusyState();

            //List<RedLineRowInfo> redLineRowInfo_list = new List<RedLineRowInfo>();
            List<IPolygon> polygon_list = new List<IPolygon>();
            foreach (var envelop in envelop_list)
            {
                //注意坐标系
                //RedLineRowInfo redLineRowInfo = new RedLineRowInfo(MyAeMethods.Instance.EnvelopToPolygonClass(envelop, MyAeMethods.Instance.GetSpatialReference_from_featureClass(_featureClass_original)), string.Empty, string.Empty, string.Empty);
                //redLineRowInfo_list.Add(redLineRowInfo);
                polygon_list.Add(MyAeMethods.Instance.EnvelopToPolygonClass(envelop, MyAeMethods.Instance.GetSpatialReference_from_featureClass(_featureClass_original)));
            }


            //往featureclass中写入数据
            //Boolean isAddSuccess = MyAeMethods.Instance.AddDatasToFeatureClass(featureClass_no_clip, redLineRowInfo_list.ToArray());

            Boolean isAddSuccess = MyAeMethods.Instance.AddDatasToFeatureClass(featureClass_no_clip,_field_name_list, polygon_list);


            


            Application.DoEvents();

            IFeatureClass clip_featureClass = null;

            string savePath2 = System.IO.Path.GetDirectoryName(_shpFullPath) + "\\" + System.IO.Path.GetFileNameWithoutExtension(_shpFullPath) + "_" + string.Format("{0}x{1}{2}", _length_original.ToString(), _length_original.ToString(), _unit) + "_" + MyMethods.Date_time_suffix();


            if (isAddSuccess == false)
            {
                MessageBox.Show("往空的FeatureClass中添加数据失败!可能在添加某一条记录时出现错误。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MyAeMethods.Instance.SetDefaultState();
                return;
            }
            else
            {
                //调用gp clip工具切割
                clip_featureClass = MyAeMethods.Instance.Clip_GP(featureClass_no_clip, _featureClass_original, savePath2);
            }


            MyAeMethods.Instance.SetDefaultState();
            if (null != clip_featureClass)
                MessageBox.Show("切割成功！结果shp文件在:\n" + savePath2, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show("切割失败！可能是gp clip工具问题", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);


        }







    }
}
